//
//  YQLoginViewController.swift
//  WeiBOSina
//
//  Created by a on 16/3/1.
//  Copyright © 2016年 CUM. All rights reserved.
//

import UIKit
import AFNetworking

class YQLoginViewController: UIViewController,UIWebViewDelegate {
    
    //授权的网页
    var webView :UIWebView?
    
    override func loadView() {
        
        webView = UIWebView()
        
        view = webView
        //设置代理监听网页
        webView?.delegate = self
        
    }
    
    /*
    
    https://api.weibo.com/oauth2/authorize?client_id=2563089702&redirect_uri=http://583306550qq.com&response_type=code
    
    */
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        view.backgroundColor = UIColor.whiteColor()
        
        setUpNav()
        
        //设置URL
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APP_key)&redirect_uri=\(APP_URL)&response_type=code")
        
        //创建请求
        let request = NSURLRequest(URL: url!)
        //加载请求
        webView?.loadRequest(request)
        
        
    }

    
    
    private func setUpNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
    }
    //返回的按钮点击
    func dismiss(){
    
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    //自动填充的按钮点击
    func auto(){
        
        let js = "document.getElementById(\"userId\").value = \"youremailname@126.com\";document.getElementById(\"passwd\").value = \"passwd\";"
        //注入到web页面
        
        webView?.stringByEvaluatingJavaScriptFromString(js)

    }
    
}



//通过extension
extension YQLoginViewController{

//    
//    Optional("https://api.weibo.com/oauth2/authorize?client_id=2563089702&redirect_uri=http://baidu.com&response_type=code")
//    Optional("https://api.weibo.com/oauth2/authorize")
//    Optional("https://api.weibo.com/oauth2/authorize#")
//    Optional("https://api.weibo.com/oauth2/authorize")
//    Optional("http://baidu.com/?code=7c51f77306a01d8f41706ccd01ea471c")
//    Optional("http://192.168.1.1/bulletin_2.htm?r=0%7Curl=baidu.com%7C")
    
    //MARK:--代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //变成了绝对路径，可以变成了string类型的
//        print(request.URL?.absoluteString)
        let URL = (request.URL?.absoluteString)! as NSString
        
//        if request.URL?.absoluteString
        if URL .hasPrefix(APP_URL){
            
            let range = URL.rangeOfString("code=")
            //截取Token
            if range.length > 0{
                
                let code  = URL.substringFromIndex(range.location + range.length)
                
//                 print(code)
                
                loadToken(code, sucess: { () -> () in
                    
                    print("成功")
                    
                    }, failur: { () -> () in
                        
                        print("失败")
                })
                
            }
            
//            URL.componentsSeparatedByString("=")返回一个被截取后的数组
            
            print(request.URL?.absoluteString)
        }
        
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }

}

extension YQLoginViewController{

    func loadToken(code:String,sucess:()->(),failur:()->()){
        
        //1.实例化manager
        let manager = AFHTTPSessionManager()
        
        //修改接收类型
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let para = ["client_id": APP_key,
            "client_secret":APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":APP_URL
        ]
        //2发送请求
        manager.POST(APP_TokenURL, parameters: para, progress: nil, success: { (_, JSON) -> Void in
            
//            print(JSON)
            let dict = JSON as? [String:NSObject]
            
            if let Odict = dict{
            
                //字典转模型
                let usrtInfo = YQUsrInfo(dict: Odict)
                
//                print(usrtInfo)
                
                self.getUserInfo(usrtInfo, sucess: sucess, failur: failur)
                
                
            }
            
            }) { (_, error) -> Void in
                //失败的时候调用
                failur()
                
                print(error)
        }
        
    }

}

//获取用户的个人数据
extension YQLoginViewController{
    
    func getUserInfo(userInfo:YQUsrInfo,sucess:()->(),failur:()->()){
        
        let manager = AFHTTPSessionManager()
        
//        必选	类型及范围	说明
//        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
//        uid	false	int64	需要查询的用户ID。
//        screen_name	false	string	需要查询的用户昵称。

        let para = ["access_token":userInfo.access_token ?? "",
                "uid":userInfo.uid ?? ""
        ]
        
        manager.GET("https://api.weibo.com/2/users/show.json", parameters: para, progress: nil, success: { (_ , JSON) -> Void in
//            print(JSON)
            //字典转模型
            let dict = JSON as? [String:NSObject]
            
            userInfo.profile_image_url = dict!["profile_image_url"] as? String
            
            userInfo.screen_name = dict!["screen_name"] as? String
            
            userInfo.save("userInfo")
            
            sucess()
            
            }) { (_ , error) -> Void in
                
                print(error)
                
                failur()
        }
        
    }
    
}